package cn.wit.test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.lang.model.element.ExecutableElement;

import com.sun.org.apache.xerces.internal.parsers.CachingParserPool.SynchronizedGrammarPool;

public class DemoProducerAndConsumer {
	public static void main(String[] args) {
		
		ExecutorService service =  Executors.newFixedThreadPool(3);
		
		Factory factory = new Factory();
		
		service.execute(new Producer(factory));
		
		service.execute(new Consumer(factory));
		
		service.execute(new Consumer(factory));
		
		service.shutdown();//关闭线程池
	}

}

class Producer implements Runnable {

	private Factory factory;

	public Producer(Factory f) {
		// TODO Auto-generated constructor stub
		this.factory = f;
	}

	@Override
	public void run() {

		try {
			// 不断生产egg
			while (true) {
				// 往工厂里面放一个产品

				factory.put();

				Thread.sleep((long) Math.random() * 100);

			}
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

class Consumer implements Runnable {
	
	private Factory factory;
	
	public Consumer(Factory factory) {
		this.factory = factory;
	}

	@Override
	public void run() {
		try {
			// 买蛋
			while (true) {
				// 往工厂里面放一个产品

				factory.buy();

				Thread.sleep((long) Math.random() * 100);

			}
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

class Factory {

	private static final int MAX = 10;

	List<Integer> eggs = new ArrayList<>();

	int id = 1;

	// 消费一个产品
	public synchronized void buy() {
		if (eggs.size() == 0) {
			System.out.println("卖完了....");
			return;
		}

		Integer last = eggs.remove(eggs.size() - 1);
		System.out.println("买到了一个蛋。。。" + last);
	}

	// 生产一个产品
	public synchronized void put() {

		if (eggs.size() >= MAX) {
			System.out.println("放不下了。。。");
			return;
		}

		System.out.println("放入了一个鸡蛋..." + id);
		eggs.add(id++);
	}
}
